/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.velocityme.session;

import com.velocityme.entity.ContactDetail;
import com.velocityme.entity.ContactDetailType;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author rcrida
 */
@Stateless
public class ContactDetailBean implements ContactDetailLocal {

    @PersistenceContext
    private EntityManager em;

    public Collection<ContactDetail> findAllContactDetails(KeyLocal key) {
        return null;
    }

    public Collection<ContactDetailType> findAllContactDetailTypes(KeyLocal key) {
        key.validateKey();
        return em.createNamedQuery("findAllContactDetailTypes").getResultList();
    }

    public void editContactDetailTypes(KeyLocal key, Collection<ContactDetailType> contactDetailTypes) {
        Map<Long,ContactDetailType> existingTypeMap = new HashMap<Long,ContactDetailType>();
        for (ContactDetailType value: findAllContactDetailTypes(key)) {
            existingTypeMap.put(value.getId(), value);
        }
        for (ContactDetailType value: contactDetailTypes) {
            // update existing ones
            if (value.getId() != null) {
                em.merge(value);
                existingTypeMap.remove(value.getId());
            }
            // create new ones
            else {
                em.persist(value);
            }
        }
        // delete remaining ones
        for (ContactDetailType value: existingTypeMap.values()) {
            for (ContactDetail cd: (List<ContactDetail>) em.createNamedQuery("findAllContactDetailByType").setParameter("contactDetailType", value).getResultList()) {
                em.remove(cd);
            }
            em.remove(value);
        }
    }


    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method" or "Web Service > Add Operation")
 
}
